package com.bruce.ai.alibaba.chat.memory.controller;

import java.util.List;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.ai.chat.messages.Message;
import com.alibaba.cloud.ai.memory.redis.RedissonRedisChatMemoryRepository;

import static org.springframework.ai.chat.memory.ChatMemory.CONVERSATION_ID;


/**
 * Redis 内存控制器
 * 提供基于 Redis 存储的聊天内存功能
 */
@RestController
@RequestMapping("/advisor/memory/redis")
public class RedisMemoryController {

    private final ChatClient chatClient;
    private final int MAX_MESSAGES = 100;
    private final MessageWindowChatMemory messageWindowChatMemory;

    public RedisMemoryController(ChatClient.Builder chatClientBuilder, RedissonRedisChatMemoryRepository redisChatMemoryRepository) {
        this.messageWindowChatMemory = MessageWindowChatMemory.builder()
                                    .chatMemoryRepository(redisChatMemoryRepository)
                                    .maxMessages(MAX_MESSAGES)
                                    .build();
       this.chatClient = chatClientBuilder.defaultAdvisors(
        MessageChatMemoryAdvisor.builder(messageWindowChatMemory)
        .build()).build();
    }


    /**
     * 调用聊天模型，使用指定的查询和对话 ID
     *
     * @param query          用户查询
     * @param conversationId 对话 ID
     * @return 模型响应内容
     */
    @GetMapping("/call")
    public String call(@RequestParam(value = "query", defaultValue = "你好，我的外号是阿斯拉达，请记住呀") String query,
                       @RequestParam(value = "conversation_id", defaultValue = "asurada") String conversationId
    ) {
        return chatClient.prompt(query)
                .advisors(
                        a -> a.param(CONVERSATION_ID, conversationId)
                )
                .call().content();
    }


    /**
     * 获取指定对话 ID 的消息列表
     *
     * @param conversationId 对话 ID
     * @return 消息列表
     */
    @GetMapping("/messages")
    public List<Message> messages(@RequestParam(value = "conversation_id", defaultValue = "asurada") String conversationId) {
        return messageWindowChatMemory.get(conversationId);
    }

}
